import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:raze/artifacts/auth_portal_dialog.dart';
import 'package:raze/artifacts/circle_join_dialog.dart';
import 'package:raze/artifacts/notifier_glimmer.dart';
import 'package:raze/artifacts/report_vault_dialog.dart';
import 'package:raze/artifacts/clickable_avatar_widget.dart';
import 'package:raze/artifacts/user_nav_bar_widget.dart';
import 'package:raze/lore/chronicle/circle_chronicle.dart';
import 'package:raze/lore/chronicle/community_chronicle.dart';
import 'package:raze/lore/chronicle/user_chronicle.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';

/// 社区页面
class CommunityRealms extends StatelessWidget {
  const CommunityRealms({super.key});

  @override
  Widget build(BuildContext context) {
    final circleChronicle = Get.find<CircleChronicle>();
    final communityChronicle = Get.find<CommunityChronicle>();
    final userChronicle = Get.find<UserChronicle>();

    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/background.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 顶部导航栏（固定）
              const UserNavBarWidget(),

              // 可滚动内容
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 海报图
                      _renderPosterBanner(),

                      // 圈子列表区域
                      _assembleCircleSection(circleChronicle),

                      // 社区列表
                      _constructCommunityList(
                        communityChronicle,
                        userChronicle,
                      ),
                      100.h.boxHeight,
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 渲染海报横幅
  Widget _renderPosterBanner() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: LayoutBuilder(
        builder: (context, constraints) {
          final imageWidth = constraints.maxWidth;
          final aspectRatio = 343 / 171;
          final imageHeight = imageWidth / aspectRatio;

          return SizedBox(
            width: imageWidth,
            height: imageHeight,
            child: Image.asset(
              'assets/images/community-poster.png',
              fit: BoxFit.fill,
            ),
          );
        },
      ),
    );
  }

  /// 组装圈子部分
  Widget _assembleCircleSection(CircleChronicle circleChronicle) {
    return Obx(() {
      final circles = circleChronicle.circleList;
      if (circles.isEmpty) {
        return const SizedBox.shrink();
      }

      // 只取前四个圈子
      final displayCircles = circles.take(4).toList();

      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题行
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('community')
                    .applyTypeSize(20.sp)
                    .applyTypeColor(RazeConstants.black)
                    .applyBagelFatOne(weight: FontWeight.w400),
                GestureDetector(
                  onTap: () {
                    // 跳转到圈子列表页面
                    Get.toNamed('/group-list');
                  },
                  child:
                      Text('See more >')
                          .applyTypeSize(12.sp)
                          .applyTypeColor(RazeConstants.black.withOpacity(0.6))
                          .applyNotoSans(),
                ),
              ],
            ),
          ),
          12.h.boxHeight,

          // 圈子卡片横向列表（不需要滚动，刚好显示四个）
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: LayoutBuilder(
              builder: (context, constraints) {
                // 计算可用宽度：屏幕宽度 - 左右padding - 三个间距
                final availableWidth = constraints.maxWidth;
                final spacing = 8.w;
                final circleWidth = (availableWidth - spacing * 3) / 4;

                final userChronicle = Get.find<UserChronicle>();
                return Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children:
                      displayCircles.asMap().entries.map((entry) {
                        final index = entry.key;
                        final circle = entry.value;
                        return Padding(
                          padding: EdgeInsets.only(
                            right:
                                index < displayCircles.length - 1 ? spacing : 0,
                          ),
                          child: _buildCircleCard(
                            circle,
                            circleWidth,
                            circleChronicle,
                            userChronicle,
                          ),
                        );
                      }).toList(),
                );
              },
            ),
          ),
          12.h.boxHeight,
        ],
      );
    });
  }

  /// 构建圈子卡片
  Widget _buildCircleCard(
    dynamic circle,
    double circleWidth,
    CircleChronicle circleChronicle,
    UserChronicle userChronicle,
  ) {
    return SizedBox(
      width: circleWidth,
      child: Column(
        children: [
          // 圈子图片
          Container(
            width: circleWidth,
            height: circleWidth,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10.r),
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(10.r),
              child: Image.asset(
                circle.image,
                width: circleWidth,
                height: circleWidth,
                fit: BoxFit.cover,
              ),
            ),
          ),
          8.h.boxHeight,

          // 圈子标题
          SizedBox(
            height: 40.h,
            child: Center(
              child: Text(
                    circle.title,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    textAlign: TextAlign.center,
                  )
                  .applyTypeSize(12.sp)
                  .applyTypeColor(RazeConstants.black)
                  .applyNotoSans(weight: FontWeight.w400),
            ),
          ),
        ],
      ),
    ).withTouchResonance(
      onTap: () => _handleCircleCardTap(circle, circleChronicle, userChronicle),
    );
  }

  /// 处理圈子卡片点击
  void _handleCircleCardTap(
    dynamic circle,
    CircleChronicle circleChronicle,
    UserChronicle userChronicle,
  ) {
    final currentUser = userChronicle.currentUser;

    // 检查登录状态
    if (currentUser == null) {
      AuthPortalDialog.revealAuthPortal();
      return;
    }

    // 检查是否已加入
    final isMember = circleChronicle.checkIsMember(circle.id, currentUser.id);

    if (isMember) {
      // 已加入：跳转到圈子聊天页面
      Get.toNamed('/group-chat', parameters: {'circleId': circle.id});
    } else {
      // 未加入：弹出确认弹窗
      CircleJoinDialog.revealJoinDialog(
        circle: circle,
        onJoinConfirmed: () {
          // 加入圈子
          circleChronicle.joinCircle(circle.id, currentUser.id);
        },
      );
    }
  }

  /// 构建社区列表
  Widget _constructCommunityList(
    CommunityChronicle communityChronicle,
    UserChronicle userChronicle,
  ) {
    return Obx(() {
      final communities = communityChronicle.communityList;
      if (communities.isEmpty) {
        return Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: Center(
            child:
                Text('No community posts yet')
                    .applyTypeSize(16.sp)
                    .applyTypeColor(RazeConstants.black.withOpacity(0.6))
                    .applyNotoSans(),
          ),
        );
      }

      // 按创建时间降序排序，最新发布的显示在最前面
      final sortedCommunities = List.from(communities)
        ..sort((a, b) => b.createTime.compareTo(a.createTime));

      return Column(
        children:
            sortedCommunities.map((community) {
              final user = userChronicle.queryUserById(community.userId);
              return _composeCommunityCard(
                community: community,
                user: user,
                communityChronicle: communityChronicle,
                userChronicle: userChronicle,
              );
            }).toList(),
      );
    });
  }

  /// 组合社区卡片
  Widget _composeCommunityCard({
    required dynamic community,
    required dynamic user,
    required CommunityChronicle communityChronicle,
    required UserChronicle userChronicle,
  }) {
    final random = Random(community.id.hashCode);
    final viewCount = random.nextInt(500) + 50;

    return GestureDetector(
      onTap: () {
        // 跳转到社区详情页面
        Get.toNamed(
          '/community-detail',
          parameters: {'communityId': community.id},
        );
      },
      child: Container(
        margin: EdgeInsets.only(left: 16.w, right: 16.w, bottom: 16.h),
        child: LayoutBuilder(
          builder: (context, constraints) {
            final cardWidth = constraints.maxWidth;
            final aspectRatio = 343 / 369;
            final cardHeight = cardWidth / aspectRatio;

            return Container(
              width: cardWidth,
              height: cardHeight,
              padding: EdgeInsets.all(12.w),
              decoration: BoxDecoration(
                color: RazeConstants.white,
                borderRadius: BorderRadius.circular(16.r),
                border: Border.all(color: RazeConstants.black, width: 2.w),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 用户信息行
                  Row(
                    children: [
                      // 用户头像
                      ClickableAvatarWidget(
                        userId: user?.id ?? '',
                        avatarPath: user?.avatar ?? 'assets/images/avatar1.png',
                        width: 40.w,
                        height: 40.w,
                      ),
                      12.w.boxWidth,
                      // 用户名和时间
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(user?.username ?? 'Unknown')
                                .applyTypeSize(18.sp)
                                .applyTypeColor(RazeConstants.black)
                                .applyNotoSans(weight: FontWeight.w600),
                            2.h.boxHeight,
                            Text(_formatTimeAgo(community.createTime))
                                .applyTypeSize(12.sp)
                                .applyTypeColor(
                                  RazeConstants.black.withOpacity(0.6),
                                )
                                .applyNotoSans(weight: FontWeight.w400),
                          ],
                        ),
                      ),
                      // 举报按钮
                      GestureDetector(
                        onTap:
                            () => _triggerReportAction(
                              community.id,
                              communityChronicle,
                            ),
                        child: Image.asset(
                          'assets/images/report.png',
                          width: 20.w,
                          height: 20.w,
                        ),
                      ),
                    ],
                  ),
                  12.h.boxHeight,

                  // 文字内容（根据内容自适应）
                  Text(
                        community.detail,
                        style: TextStyle(
                          fontFamily:
                              GoogleFonts.openSans(
                                fontWeight: FontWeight.w400,
                              ).fontFamily,
                          height: 1.67,
                        ),
                      )
                      .applyTypeSize(14.sp)
                      .applyTypeColor(const Color(0xFF1B3738)),
                  12.h.boxHeight,

                  // 媒体内容（图片或视频，撑满剩余空间）
                  Expanded(child: _renderMediaContent(community)),
                  12.h.boxHeight,

                  // 底部操作栏
                  Row(
                    children: [
                      // 点赞按钮和数量
                      Row(
                        children: [
                          GestureDetector(
                            onTap: () {
                              final currentUser = userChronicle.currentUser;
                              if (currentUser == null) {
                                // 未登录，显示登录提示弹窗
                                AuthPortalDialog.revealAuthPortal();
                                return;
                              }

                              final hasLiked = communityChronicle
                                  .checkCommunityLiked(
                                    currentUser.id,
                                    community.id,
                                  );
                              if (hasLiked) {
                                communityChronicle.unlikeCommunity(
                                  currentUser.id,
                                  community.id,
                                );
                              } else {
                                communityChronicle.likeCommunity(
                                  currentUser.id,
                                  community.id,
                                );
                              }
                            },
                            child: Obx(() {
                              final currentUser = userChronicle.currentUser;
                              final liked =
                                  currentUser != null &&
                                  communityChronicle.checkCommunityLiked(
                                    currentUser.id,
                                    community.id,
                                  );

                              return Image.asset(
                                liked
                                    ? 'assets/images/like.png'
                                    : 'assets/images/unlike.png',
                                width: 22.w,
                                height: 22.w,
                                color: liked ? RazeConstants.red : null,
                              );
                            }),
                          ),
                          8.w.boxWidth,
                          Obx(() {
                            final updatedCommunity =
                                communityChronicle.communityList
                                    .firstWhereOrNull(
                                      (c) => c.id == community.id,
                                    ) ??
                                community;
                            return Text('${updatedCommunity.likeCount}')
                                .applyTypeSize(14.sp)
                                .applyTypeColor(RazeConstants.black)
                                .applyNotoSans(weight: FontWeight.w600);
                          }),
                        ],
                      ),
                      24.w.boxWidth,

                      // 评论图标和数量
                      Row(
                        children: [
                          Image.asset(
                            'assets/images/message.png',
                            width: 18.w,
                            height: 18.w,
                          ),
                          8.w.boxWidth,
                          Text(
                                '${communityChronicle.fetchComments(community.id).length}',
                              )
                              .applyTypeSize(14.sp)
                              .applyTypeColor(RazeConstants.black)
                              .applyNotoSans(weight: FontWeight.w600),
                        ],
                      ),
                      24.w.boxWidth,

                      // 查看图标和数量
                      Row(
                        children: [
                          Icon(
                            Icons.visibility_rounded,
                            size: 20.sp,
                            color: RazeConstants.black,
                          ),
                          8.w.boxWidth,
                          Text('$viewCount')
                              .applyTypeSize(14.sp)
                              .applyTypeColor(RazeConstants.black)
                              .applyNotoSans(weight: FontWeight.w600),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ).withRightBottomShadow(thickness: 2);
          },
        ),
      ),
    );
  }

  /// 渲染媒体内容
  Widget _renderMediaContent(dynamic community) {
    if (community.contentType == 'image') {
      return ClipRRect(
        borderRadius: BorderRadius.circular(12.r),
        child: Image.asset(
          community.media,
          width: double.infinity,
          height: double.infinity,
          fit: BoxFit.cover,
        ),
      );
    } else if (community.contentType == 'video') {
      return Stack(
        alignment: Alignment.center,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(12.r),
            child: Image.asset(
              community.coverImage ?? '',
              width: double.infinity,
              height: double.infinity,
              fit: BoxFit.cover,
            ),
          ),
          // 播放图标
          Container(
            width: 56.w,
            height: 56.w,
            decoration: BoxDecoration(
              color: RazeConstants.white.withOpacity(0.9),
              shape: BoxShape.circle,
              border: Border.all(color: RazeConstants.black, width: 2.w),
            ),
            child: Icon(
              Icons.play_arrow_rounded,
              size: 36.w,
              color: RazeConstants.black,
            ),
          ).withRightBottomShadow(thickness: 1.5),
        ],
      );
    }
    return const SizedBox.shrink();
  }

  /// 格式化时间（如：5 Min Ago）
  String _formatTimeAgo(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${difference.inDays} Day${difference.inDays > 1 ? 's' : ''} Ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours} Hour${difference.inHours > 1 ? 's' : ''} Ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes} Min Ago';
    } else {
      return 'Just Now';
    }
  }

  /// 触发举报操作
  void _triggerReportAction(
    String communityId,
    CommunityChronicle communityChronicle,
  ) {
    ReportVaultDialog.revealReportVault(
      onReportSubmitted: (_) {
        // 举报成功提示
        NotifierGlimmer.revealInfo('Report submitted successfully.');

        // 删除被举报的社区帖子
        communityChronicle.deleteCommunityById(communityId);
      },
    );
  }
}
